/**
 * Copyright (c) 2023 myons Inc. All rights reserved.
 */
package cn.zmwh.im.server.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;

/**
 * @describe: 动态表名 、
 * @author: dmzmwh 、
 * @time: 2023-12-28 11:01 、
 */
public class DpTableNameHandler implements TableNameHandler {


    /**
     * 每个请求线程维护一个数据，避免多线程数据冲突。所以使用ThreadLocal
     */
    private static final ThreadLocal<Integer> SUFFIX = new ThreadLocal<>();

    /**
     * 设置请求线程的month数据
     *
     * @param suffix
     */
    public static void setData(Integer suffix) {
        SUFFIX.remove();
        SUFFIX.set(suffix);
    }

    /**
     * 清除
     */
    public static void isClear() {
        Integer suffix = SUFFIX.get();
        if (suffix != null) {
            SUFFIX.remove();
        }
    }

    /**
     * 清除
     */
    public static void clear() {
        SUFFIX.remove();
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        Integer suffix = SUFFIX.get();
        if (suffix == null) {
            return tableName;
        }
        if (tableName.contains("`")) {
            tableName = tableName.replace("`", "");
        }
        return tableName + "_" + suffix;
    }
}
